package com.atguigu.paymentdemo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * @create 2022-12-17
 * @comment
 **/
@Slf4j
public class JsonUtil {
    private static ObjectMapper om;

    private static final Logger LOG = LoggerFactory.getLogger(JsonUtil.class);

    static {
        om = new ObjectMapper();
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    public static String encode(Object object) {
        try {
            return om.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            LOG.error("object to jsonStr exception object {}", object, e);
            return "";
        }
    }

    /**
     * @param json
     * @param tClass
     * @return
* @date 2019-08-20 17:28
     */
    public static <T> T decode(String json, Class<T> tClass) {
        try {
            return om.readValue(json, tClass);
        } catch (IOException e) {
            log.error("decode error", e);
        }
        return null;
    }

    /**
     * 解析json
     *
     * @param json
     * @param typeReference
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T decode(String json, TypeReference<T> typeReference) throws IOException {
        return om.readValue(json, typeReference);
    }


    public static Map<String, Object> decode(String json) throws Exception {
        try {
            return (Map) om.readValue(json, new TypeReference<Map<String, Object>>() {
            });
        } catch (IOException e) {
            LOG.error("jsonStr to obejct exception jsonStr {}", json, e);
            return null;
        }
    }
}
